<template>
  <div class="view-image" @click.self="handleClose">
    <div id="thumbnail" class="thumbnail">
      <div
        id="indicator"
        @mousemove="handleMouseMove"
        @mouseleave="handleMouseLeave"
        @contextmenu.prevent.stop
        class="indicator"
      ></div>
      <img
        id="imgbgRef"
        @mousemove="handleMouseMove"
        @mouseleave="handleMouseLeave"
        @contextmenu.prevent.stop
        :src="src"
        class="imgbg"
      />
    </div>
    <div
      id="imageContainer"
      @mousemove="handleMouseMove"
      @mouseleave="handleMouseLeave"
      @contextmenu.prevent.stop
      class="thumbnail-container"
    >
      <canvas id="imageCanvas" />
    </div>
    <div class="image-view-exit el-icon-close" title="关闭" @click="handleClose" />
    <div class="image-view-btn" @click.stop="handleClick">查看原图</div>
    <div
      v-if="isInside"
      :style="{
        background: `url(${src}) no-repeat`,
        backgroundSize: `${ow * scale}px ${oh * scale}px`,
        backgroundPosition,
        left: preLeft / sw > 0.6 ? 0 : sw - 352 + 'px',
      }"
      class="cx-cropper-selection-glass"
    >
      <div class="cx-cropper-selection-glass__line is-horizontal"></div>
      <div class="cx-cropper-selection-glass__line is-vertical"></div>
      <div class="cx-cropper-selection-glass__mark"></div>
    </div>
  </div>
</template>
<script>
export default {
  name: "ViewImage",
  props: {
    // 预览图片地址
    src: {
      type: String,
      default: "",
    },
    // 开始坐标
    start: {
      type: Array,
      default: [0, 0],
    },
    // 结束坐标
    end: {
      type: Array,
      default: [0, 0],
    },
    // 缩放比例
    scale: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      ow: 0,
      oh: 0,
      isInside: false,
      backgroundPosition: "0 0",
      preLeft: 0,
      sw: 0,
      imgMarginLeft: 0,
      imgMarginTop: 0,
    };
  },
  mounted() {
    this.init();
    window.addEventListener("resize", this.init);
  },
  methods: {
    async init() {
      await this.getOriginSize();
      this.parseCoordinate();
    },
    // 获取缩略图
    getOriginSize() {
      return new Promise((resolve) => {
        const img = new Image();
        img.src = this.src;
        img.onload = () => {
          this.ow = img.width;
          this.oh = img.height;
          resolve();
        };
      });
    },
    // 解析坐标
    parseCoordinate() {
      const [x, y] = this.start;
      const [x1, y1] = this.end;
      let w = x1 - x;
      let h = y1 - y;
      let thumbnail = document.getElementById("thumbnail");
      let xscale = this.ow / thumbnail.offsetWidth;
      let yscale = this.oh / thumbnail.offsetHeight;

      let indicator = document.getElementById("indicator");
      let imageContainer = document.getElementById("imageContainer");
      let left = x / xscale - w / xscale;
      let top = y / yscale - h / yscale;
      indicator.style.left = `${left}px`;
      indicator.style.top = `${top}px`;
      indicator.style.width = `${(w / xscale) * 3}px`;
      indicator.style.height = `${(h / yscale) * 3}px`;
      indicator.style.setProperty("--lineTop", `-${window.innerHeight}px`);
      indicator.style.display = "block";

      imageContainer.style.left = `${
        left + window.innerWidth * 0.05 - (w / xscale) * 5
      }px`;
      this.cropImage(w * 2, h * 2, x, y);
    },
    // 剪切图片
    cropImage(w, h, x, y) {
      let canvas = document.getElementById("imageCanvas");
      const ctx = canvas.getContext("2d");
      const img = new Image();
      img.src = this.src;
      img.onload = () => {
        canvas.width = w;
        canvas.height = h;
        ctx.drawImage(
          img,
          x - w / 4,
          y - h / 4,
          this.ow,
          this.oh,
          0,
          0,
          this.ow,
          this.oh
        );
      };
    },
    // 关闭事件
    handleClose() {
      this.isInside = false;
      this.$emit("close");
    },
    // 查看大图
    handleClick() {
      window.open(this.src, "_blank");
    },
    // 鼠标移入打开放大镜
    handleMouseMove(e) {
      const rect = e.currentTarget.getBoundingClientRect();
      if (e.target.id === "imgbgRef") {
        this.imgMarginLeft = rect.left;
        this.imgMarginTop = rect.top;
      }
      const offsetX = e.clientX - (this.imgMarginLeft || rect.left);
      const offsetY = e.clientY - (this.imgMarginTop || rect.top);
      this.isInside = true;
      this.setGlassPosition(offsetX, offsetY);
    },
    // 鼠标移出关闭放大镜
    handleMouseLeave() {
      this.isInside = false;
    },
    // 设置坐标
    setGlassPosition(left, top) {
      let imgw = window.innerWidth * 0.9;
      let widthRatio = this.ow / imgw;
      let imgh = window.innerHeight * 0.9;
      let heightRatio = this.oh / imgh;
      let offsetX = left * this.scale * widthRatio - this.imgMarginLeft * 2;
      let offsetY = top * this.scale * heightRatio - this.imgMarginTop * 2;
      this.preLeft = left;
      this.sw = window.innerWidth;
      this.backgroundPosition = `-${offsetX}px -${offsetY}px`;
    },
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.init);
    const thumbnail = document.getElementById("thumbnail");
    if (thumbnail) {
      thumbnail.removeEventListener("mousemove", this.handleMouseMove);
      thumbnail.removeEventListener("mouseleave", this.handleMouseLeave);
    }
  },
};
</script>
<style lang="scss" scoped>
.view-image {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  z-index: 99999;
  display: flex;
  align-items: center;
  justify-content: center;
  .thumbnail {
    position: relative;
    overflow: hidden;
    width: 90vw;
    height: 90vh;
    .imgbg {
      position: absolute;
      top: 0;
      left: 0;
    }
    img {
      width: 100%;
      height: 100%;
    }
    .indicator {
      display: none;
      --lineTop: 0;
      position: absolute;
      border: 2px solid #f00;
      z-index: 9;
      &::after {
        content: "";
        position: absolute;
        left: -2px;
        bottom: 0;
        top: var(--lineTop);
        width: 2px;
        background-color: #f00;
      }
    }
  }
  .thumbnail-container {
    position: absolute;
    top: 20px;
    z-index: 9;
  }
  .image-view-exit {
    position: absolute;
    top: 20px;
    right: 20px;
    z-index: 9;
    color: #fff;
    border-radius: 50%;
    font-size: 30px;
    &:hover {
      cursor: pointer;
      color: #a0a0a0;
    }
  }
  .image-view-btn {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 9;
    color: #fff;
    font-size: 14px;
    padding: 4px 10px;
    background-color: #409eff;
    &:hover {
      cursor: pointer;
      background-color: #447ed9;
    }
  }
}
.cx-cropper-selection-glass {
  width: 350px;
  height: 280px;
  position: absolute;
  top: 0;
  border: 1px solid #000;
  z-index: 30;
  pointer-events: none;
  background-repeat: no-repeat;
  box-sizing: border-box;
  background-color: #fff;
  transition: left 0.3s;
  .cx-cropper-selection-glass__line {
    position: absolute;
    background: rgba(#447ed9, 0.5);

    &.is-vertical {
      width: 5px;
      height: 100%;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
    }

    &.is-horizontal {
      width: 100%;
      height: 5px;
      top: 50%;
      left: 0;
      transform: translateY(-50%);
    }
  }

  .cx-cropper-selection-glass__mark {
    width: 5px;
    height: 5px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid #000;
    background: #fff;
  }
}
</style>
